﻿using Magic.Core.Entity;
using Magic.Core.Service;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace ManagementTools
{
    internal static class App
    {
        public static int TenentId { get; } = 0;
        public static SqlSugarClient SugarClient { get; private set; }
        public static LoginInput LoginUser { get; set; }
        public static string ApiServer { get;private set; }
        public static string Token { get; set; }
        public static void StartUp()
        {
            ApiServer = System.Configuration.ConfigurationManager.AppSettings["ApiServer"]??"http://localhost:5566";

            var tenant = ConfigHelper.GetSection($"ConnectionStrings:DbConfigs:{TenentId}");
            var connString = tenant.GetSection("DbString").Value;
            var typeText = tenant.GetSection("DbType").Value;
            var dbType = (SqlSugar.DbType)Convert.ToInt32(Enum.Parse(typeof(SqlSugar.DbType), typeText));
            SugarClient= new SqlSugarClient(new ConnectionConfig()
            {
                DbType = dbType,
                ConnectionString = connString,
                IsAutoCloseConnection = true,
                ConfigureExternalServices = new ConfigureExternalServices
                {
                    EntityService = (c, p) =>
                    {
                        // int?  decimal?这种 isnullable=true
                        if (c.PropertyType.IsGenericType &&
                        c.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
                        {
                            p.IsNullable = true;
                        }
                        else if (c.PropertyType == typeof(string) && c.GetCustomAttribute<RequiredAttribute>() == null)
                        { //string类型如果没有Required isnullable=true
                            p.IsNullable = true;
                        }

                    }
                }
            });
            SugarClient.Aop.OnLogExecuting = (sql, pars) =>
            {
                Debug.WriteLine(sql);//输出sql
                Debug.WriteLine(string.Join(",", pars?.Select(it => it.ParameterName + ":" + it.Value)));//参数
            };
            
        }

    }
}
